from django.shortcuts import render
import json
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.core.exceptions import ObjectDoesNotExist

# Create your views here.
def index_views(request):
    table_data = [
        {"id": 1, "name": "产品 A", "category": "电子产品", "sales": 15000, "profit": 4500, "region": "华东"},
        {"id": 2, "name": "产品 B", "category": "家居用品", "sales": 8900, "profit": 2100, "region": "华南"},
        {"id": 3, "name": "产品 C", "category": "服装", "sales": 12500, "profit": 3800, "region": "华北"},
        {"id": 4, "name": "产品 D", "category": "食品", "sales": 7600, "profit": 1900, "region": "华东"},
        {"id": 5, "name": "产品 E", "category": "电子产品", "sales": 21000, "profit": 6200, "region": "华南"},
        {"id": 6, "name": "产品 F", "category": "家居用品", "sales": 5400, "profit": 1300, "region": "西南"},
        {"id": 7, "name": "产品 G", "category": "服装", "sales": 9800, "profit": 2900, "region": "华东"},
        {"id": 8, "name": "产品 H", "category": "食品", "sales": 11200, "profit": 2700, "region": "华北"},
        {"id": 9, "name": "产品 I", "category": "电子产品", "sales": 17500, "profit": 5200, "region": "华南"},
        {"id": 10, "name": "产品 J", "category": "家居用品", "sales": 6800, "profit": 1600, "region": "华东"},
        {"id": 11, "name": "产品 A", "category": "电子产品", "sales": 15000, "profit": 4500, "region": "华东"},
        {"id": 12, "name": "产品 B", "category": "家居用品", "sales": 8900, "profit": 2100, "region": "华南"},
        {"id": 13, "name": "产品 C", "category": "服装", "sales": 12500, "profit": 3800, "region": "华北"},
        {"id": 14, "name": "产品 D", "category": "食品", "sales": 7600, "profit": 1900, "region": "华东"},
        {"id": 15, "name": "产品 E", "category": "电子产品", "sales": 21000, "profit": 6200, "region": "华南"},
        {"id": 16, "name": "产品 F", "category": "家居用品", "sales": 5400, "profit": 1300, "region": "西南"},
        {"id": 17, "name": "产品 G", "category": "服装", "sales": 9800, "profit": 2900, "region": "华东"},
        {"id": 18, "name": "产品 H", "category": "食品", "sales": 11200, "profit": 2700, "region": "华北"},
        {"id": 19, "name": "产品 I", "category": "电子产品", "sales": 17500, "profit": 5200, "region": "华南"},
        {"id": 20, "name": "产品 J", "category": "家居用品", "sales": 6800, "profit": 1600, "region": "华东"},
        {"id": 21, "name": "产品 A", "category": "电子产品", "sales": 15000, "profit": 4500, "region": "华东"},
        {"id": 22, "name": "产品 B", "category": "家居用品", "sales": 8900, "profit": 2100, "region": "华南"},
        {"id": 23, "name": "产品 C", "category": "服装", "sales": 12500, "profit": 3800, "region": "华北"},
        {"id": 24, "name": "产品 D", "category": "食品", "sales": 7600, "profit": 1900, "region": "华东"},
        {"id": 25, "name": "产品 E", "category": "电子产品", "sales": 21000, "profit": 6200, "region": "华南"},
        {"id": 26, "name": "产品 F", "category": "家居用品", "sales": 5400, "profit": 1300, "region": "西南"},
        {"id": 27, "name": "产品 G", "category": "服装", "sales": 9800, "profit": 2900, "region": "华东"},
        {"id": 28, "name": "产品 H", "category": "食品", "sales": 11200, "profit": 2700, "region": "华北"},
        {"id": 29, "name": "产品 I", "category": "电子产品", "sales": 17500, "profit": 5200, "region": "华南"},
        {"id": 30, "name": "产品 J", "category": "家居用品", "sales": 6800, "profit": 1600, "region": "华东"},
    ]
    
    # 为 ECharts 柱状图准备数据
    chart_data = {
        "categories": ["产品 A", "产品 B", "产品 C", "产品 D", "产品 E", "产品 F", "产品 G", "产品 H", "产品 I", "产品 J"],
        "sales": [15000, 8900, 12500, 7600, 21000, 5400, 9800, 11200, 17500, 6800],
        "profits": [4500, 2100, 3800, 1900, 6200, 1300, 2900, 2700, 5200, 1600]
    }
    
    # 统计数据
    stats = {
        "total_sales": sum(item["sales"] for item in table_data),
        "total_profit": sum(item["profit"] for item in table_data),
        "avg_sales": sum(item["sales"] for item in table_data) / len(table_data),
        "product_count": len(table_data)
    }
    
    context = {
        # 'table_data': json.dumps(table_data),
        # 'chart_data': json.dumps(chart_data),
        'table_data': table_data,
        'chart_data': chart_data,
        'stats': stats,
        'page_title': '销售数据分析仪表板'
    }
    # print(context)
    return render(request, "home.html", context)


def test_views(request):

    return render(request, "detail.html")

def login_views(request):
    return render(request, "login.html")


@method_decorator(csrf_exempt, name="dispatch")
class UpdateView(View):
    def patch(self, request, category, object_id, item):
        try:
            if category == "object1":
                object = object1.objects.get(id=object_id)
            elif category == "object2":
                object = object2.objects.get(id=object_id)
            elif category == "object3":
                object = object3.objects.get(id=object_id)
        except ObjectDoesNotExist:
            return JsonResponse({"error": f"{category}的{object_id}不存在"}, status=404)
        try:
            data = json.loads(request.body):
        except json.JSONDecodeError:
            return JsonResponse({"error": f"{category}的{object_id}  Invalid JSON data."}, status=400)

        udpate_fields = []
        for field , value in data.items():
            if hash(object, field):
                setattr(object, field, value)
                update_field.append(field)
        object.save(udpate_field=update_fields)
        object.values
        return JsonResponse({}, status=200)
# 20251027
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import json
from .models import Product  # 假设你的模型是 Product

def edit_product(request, product_id):
    """编辑产品页面"""
    try:
        product = Product.objects.get(id=product_id)
        
        # 将模型数据转换为 JSON
        product_data = {
            'id': product.id,
            'name': product.name,
            'price': float(product.price) if product.price else 0,
            'stock_quantity': product.stock_quantity,
            'weight': float(product.weight) if product.weight else 0,
            'category': product.category,
            'description': product.description or '',
            'is_active': product.is_active,
            'is_featured': product.is_featured,
            'created_at': product.created_at.strftime('%Y-%m-%d') if product.created_at else '',
            'updated_at': product.updated_at.strftime('%Y-%m-%d') if product.updated_at else '',
        }
        
        # 可选选项数据
        category_options = [
            {'value': 'electronics', 'text': '电子产品'},
            {'value': 'clothing', 'text': '服装'},
            {'value': 'books', 'text': '图书'},
            {'value': 'other', 'text': '其他'}
        ]
        
        context = {
            'product_data': product_data,
            'category_options': category_options,
        }
        
        return render(request, 'edit_product.html', context)
        
    except Product.DoesNotExist:
        return render(request, 'error.html', {'error': '产品不存在'})

@csrf_exempt
@require_http_methods(["POST"])
def update_product(request, product_id):
    """更新产品数据"""
    try:
        data = json.loads(request.body)
        
        product = Product.objects.get(id=product_id)
        
        # 更新字段
        product.name = data.get('name', product.name)
        product.price = data.get('price', product.price)
        product.stock_quantity = data.get('stock_quantity', product.stock_quantity)
        product.weight = data.get('weight', product.weight)
        product.category = data.get('category', product.category)
        product.description = data.get('description', product.description)
        product.is_active = data.get('is_active', product.is_active)
        product.is_featured = data.get('is_featured', product.is_featured)
        product.updated_at = data.get('updated_at', product.updated_at)
        
        product.save()
        
        return JsonResponse({
            'success': True,
            'message': '更新成功'
        })
        
    except Product.DoesNotExist:
        return JsonResponse({
            'success': False,
            'error': '产品不存在'
        }, status=404)
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': str(e)
        }, status=500)


# 20251101

# views.py
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import json

@login_required
def product_form_view(request):
    """产品表单页面视图"""
    # 获取用户权限
    is_admin = request.user.is_staff or request.user.is_superuser
    
    # 准备下拉框选项数据
    code_options = [
        {
            'value': 'PROD001',
            'text': '笔记本电脑',
            'details': {
                'field2': '高性能商务笔记本',
                'field3': 'Intel i7, 16GB RAM, 512GB SSD',
                'field4': '2.5',
                'field5': '8999.99',
                'field6': '电子产品',
                'date_field': '2024-01-15'
            }
        },
        {
            'value': 'PROD002',
            'text': '智能手机',
            'details': {
                'field2': '旗舰级智能手机',
                'field3': 'Snapdragon 8 Gen 2, 12GB RAM, 256GB',
                'field4': '0.2',
                'field5': '5999.50',
                'field6': '手机',
                'date_field': '2024-02-20'
            }
        },
        {
            'value': 'PROD003',
            'text': '无线耳机',
            'details': {
                'field2': '主动降噪无线耳机',
                'field3': 'Bluetooth 5.2, 30小时续航',
                'field4': '0.1',
                'field5': '1299.99',
                'field6': '音频设备',
                'date_field': '2024-03-10'
            }
        }
    ]
    
    # 初始选中的值（可选）
    initial_code = 'PROD001'
    
    context = {
        'is_admin': is_admin,
        'code_options': code_options,
        'initial_code': initial_code,
        'csrf_token': request.csrf_token,
    }
    
    return render(request, 'product_form.html', context)

@csrf_exempt
@require_http_methods(["POST"])
def submit_product_form(request):
    """处理表单提交"""
    try:
        data = json.loads(request.body)
        print("接收到的表单数据:", data)
        
        # 这里可以处理实际的业务逻辑
        # 例如保存到数据库等
        
        return JsonResponse({
            'success': True,
            'message': '表单提交成功！',
            'received_data': data
        })
        
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': str(e)
        }, status=400)